package com.cskaoyan.service;

import com.cskaoyan.bean.entity.Role;
import com.cskaoyan.bean.entity.RoleExample;
import com.cskaoyan.bean.vo.BasePageData;
import com.cskaoyan.bean.vo.BaseParam;
import com.cskaoyan.bean.vo.RoleCommonRespVo;
import com.cskaoyan.bean.vo.RoleOptionsRespVo;
import com.cskaoyan.common.util.BeansCopyUtils;
import com.cskaoyan.common.util.StringUtils;
import com.cskaoyan.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: GaoJia
 * @Date: 2021/10/18 21:10
 */
@Service
public class RoleServiceImpl implements  RoleService {

    @Resource
    RoleMapper roleMapper;


    @Override
    public BasePageData options() {
        PageHelper.startPage(1,1);

        LinkedList<RoleOptionsRespVo> optionsList = new LinkedList<>();
        RoleExample roleExample = new RoleExample();
        List<Role> roles = roleMapper.selectByExample(new RoleExample());
        for (Role role : roles) {
            for (RoleOptionsRespVo vo : optionsList) {
                vo.setValue(role.getId());
                vo.setLabel(role.getName());
            }
        }

        return BasePageData.ok(optionsList);
    }


    @Override
    public BasePageData query(String name, BaseParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());

        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Role> roles = roleMapper.selectByExample(example);

        return BasePageData.ok(roles);
    }

    @Override
    public int update(Role role) {
        role.setUpdateTime(new Date());
        int i = roleMapper.updateByPrimaryKey(role);
        return i;
    }

    @Override
    public RoleCommonRespVo create(Map map) {
        // 获取参数
        String name = (String) map.get("name");
        String desc = (String) map.get("desc");

        Role role = new Role();
        Date date = new Date();
        role.setName(name);
        role.setDesc(desc);
        role.setAddTime(date);
        role.setUpdateTime(date);

        // 判空
        if (StringUtils.isEmpty(name)) return null;
        int i = roleMapper.insertSelective(role);
        // 查询 ID
        RoleExample roleExample = new RoleExample();
        roleExample.setOrderByClause("add_time desc");
        List<Role> roleList = roleMapper.selectByExample(roleExample);

        return BeansCopyUtils.copy(roleList.get(0), RoleCommonRespVo.class);
    }

    @Override
    public int delete(Integer id) {

        return roleMapper.deleteByPrimaryKey(id);
    }

}
